import { memo, useEffect, useState } from 'react';
import { Input, Button, AutoComplete, Tag } from 'antd';
import type { AutoCompleteProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '@/components/icon';
const { TextArea } = Input;
import { useChatPage, useConfigActions, useInitializeData } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import { useNavigate } from 'react-router-dom';

import { CloseOutlined } from '@ant-design/icons';
import '../index.css';

import { useIsDeepMode, useChatActions } from '@/store/chatStore';
import { LicenseEditionEnum } from '@/common';

const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;
import LicenseModal from '@/pages/components/modal/LicenseConfirm';

interface Props {
  handleSend: (message: string) => void;
  handleInterrupt: () => void;
  changeInputType: () => void;
  isMessageSend: boolean;
  isHome: boolean;
  voice?: boolean;
}

const MessageSendInput = ({
  handleSend,
  handleInterrupt,
  changeInputType,
  isMessageSend,
  isHome,
  voice,
}: Props) => {
  const navigate = useNavigate();

  const { isPc } = useWindowWidth();
  const [inputValue, setInputValue] = useState('');

  // const [isDeepMode, setIsDeepMode] = useState(false);
  const isDeepMode = useIsDeepMode();
  const { setIsDeepMode } = useChatActions();

  const [tag, setTag] = useState([]);
  const chatPage = useChatPage();
  const router = useRouter();
  const [actOptions, setActOptions] = useState({ value: '应用推荐', id: 1 });

  const initializeData = useInitializeData()
  const isDisabled = inputValue.trim().length === 0 && !isMessageSend && initializeData?.license_edition === LicenseEditionEnum.basic;

  const [options, setOptions] = useState<AutoCompleteProps['options']>([]);
  const onSelect = (value, option: any) => {
    console.log('onSelect', value, option);
    setTag([option]);
    setInputValue('');
  };

  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const { fetchInitialInfo } = useConfigActions();
  useEffect(() => {
    const init = async () => {
      fetchInitialInfo();
    };
    init();
  }, []);

  const demoOptions = [
    // {
    //   value: '应用推荐',
    //   id: 1,
    //   label: (
    //     <div
    //       style={{
    //         display: 'flex',
    //         // justifyContent: 'space-between',
    //         alignItems: 'center',
    //         height: '34px',
    //       }}
    //     >
    //       <SvgIcon icon="hot-fire" color="#C966FF" style={{ marginRight: '10px' }}></SvgIcon>
    //       <span style={{ fontWeight: 'bold', marginRight: '10px' }}>应用推荐</span>
    //       <span style={{ color: 'grey' }}> 各部门应用，一步到位</span>
    //     </div>
    //   ),
    //   unselectable: 'on',
    // },
  ];

  const handleSearch = (value: string) => {
    // console.log('value===========', value);

    if (value == '@' && tag.length == 0 && demoOptions?.length > 0) {
      setOptions(demoOptions);
    } else {
      setOptions([]);
    }
  };

  useEffect(() => {
    if (tag.length > 0 && options?.length != 0) {
      setOptions([]);
    }
  }, [tag.length]);

  const handleKeyDown = (e) => {
    if (e?.key === 'Delete' || e?.keyCode === 46 || e?.key === 'Backspace' || e?.keyCode === 8) {
      if (!inputValue) {
        setTag([]);
        setOptions([]);
      }
    }

    if (e?.key === 'Enter' && e?.keyCode === 13 && !e?.shiftKey) {
      if (inputValue == '@' && tag.length == 0) {
        console.log('e==========', e);
        // setTag([option]);
        setInputValue('');
        return;
      }
      e.preventDefault();
      if (!inputValue) {
        return;
      }

      console.log(tag, chatPage);
      if (licenseFlag && !initializeData?.is_license_valid) {
        handleActivateClick();
        return;
      }
      if (isHome) {
        router.pushQuery(chatPage, {
          msg: tag?.length > 0 ? '@' + tag[0]?.value + ' ' + inputValue : inputValue,
        });
      } else {
        if (tag?.length > 0) {
          handleSend('@' + tag[0]?.value + ' ' + inputValue);
        } else {
          handleSend(inputValue);
        }
        setInputValue('');
      }
    }
  };

  const handleBtnClicked = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    if (isHome) {
      // if (!inputValue) {
      //   return;
      // }
      // router.pushQuery(chatPage, {
      //   msg: tag?.length > 0 ? '@' + tag[0]?.value + ' ' + inputValue : inputValue,
      // });

      if (inputValue.trim().length == 0) {
        initializeData?.license_edition != LicenseEditionEnum?.basic && changeInputType();
      } else {
        router.pushQuery(chatPage, {
          msg: tag?.length > 0 ? '@' + tag[0]?.value + ' ' + inputValue : inputValue,
        });
      }
    } else {
      if (isMessageSend) {
        handleInterrupt();
      } else {
        if (inputValue.trim().length == 0) {
          initializeData?.license_edition != LicenseEditionEnum?.basic && changeInputType();
        } else {
          if (tag?.length > 0) {
            handleSend('@' + tag[0]?.value + ' ' + inputValue);
          } else {
            handleSend(inputValue);
          }

          setInputValue('');
        }
      }
    }
  };

  const textareaStyle = {
    borderRadius: '6px',
    resize: 'none',
    overflowY: 'scroll',
    width: '100%',
    outline: 'none',
    boxShadow: 'none',
    backgroundColor: '#fff',
    scrollbarWidth: 'none',
    flexGrow: 1,
    borderWidth: 0,
    lineHeight: '30px',
  };

  const dropdownRender = (menu) => (
    <div style={{ position: 'relative', paddingTop: '30px' }}>
      <div
        style={{
          position: 'absolute',
          top: 0,
          right: 0,
          zIndex: 1001,
          width: '100%',
          display: 'flex',
          padding: '0px 10px',
          height: '30px',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <div style={{ fontWeight: 'bold' }}>{''}</div>
        <Button
          size="small"
          type="text"
          icon={<CloseOutlined />}
          onClick={() => {
            // console.log(111111111, menu);

            setOptions([]);
          }}
        ></Button>
      </div>

      {menu}
    </div>
  );

  return (
    <div
      className="arae-outlined"
      style={{
        display: isPc ? 'flex' : 'block',
        width: '100%',
        flexDirection: 'column',
        // border: '1px solid #D1C5FF',
        backgroundColor: '#fff',
        borderRadius: '16px',
        padding: '5px',
        position: 'relative',
      }}
    >
      {tag?.length > 0 && (
        <div style={{ marginBottom: '0px' }}>
          {tag?.map((item, index) => {
            return (
              <Tag
                style={{
                  borderRadius: '5px',
                  padding: '0px 10px',
                  fontSize: '14px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  backgroundColor: 'f3f5fc',
                  fontWeight: 'bold',
                }}
                bordered={false}
                key={index}
                closable
                onClose={() => {
                  setTag([]);
                }}
              >
                @{item.value}
              </Tag>
            );
          })}
        </div>
      )}
      <div style={{ display: 'flex', width: '100%' }}>
        <AutoComplete
          className="ant-select"
          options={options}
          maxLength={2000}
          onSelect={onSelect}
          onSearch={handleSearch}
          getPopupContainer={(triggerNode) => triggerNode.parentElement}
          // placement="top"
          // autoFocus={true}
          defaultActiveFirstOption={true}
          dropdownStyle={
            isHome
              ? {
                position: 'absolute',
                top: '100%',
                left: 0,
                marginTop: 50,
                zIndex: 2000,
                borderRadius: '12px',
                width: '100%',
              }
              : {
                position: 'absolute',
                bottom: 'calc(100% + 10px)',
                // top: '-100%',
                left: 0,
                // marginTop: -25,
                zIndex: 2000,
                borderRadius: '12px',
                width: '100%',
              }
          }
          dropdownRender={dropdownRender}
          value={inputValue}
          style={{
            width: '100%',
            flex: '1 1 auto',
            height: '100%',
          }}
        >
          <TextArea
            id="question"
            className="focu border:none "
            // rows={tag?.length > 0 ? 3 : 4}
            autoSize={{ minRows: 2, maxRows: 8 }}
            onChange={(e) => setInputValue(e.target.value)}
            value={inputValue}
            onKeyDown={handleKeyDown}
            placeholder={
              isPc
                ? tag?.length == 0 && demoOptions?.length > 0
                  ? '@召唤应用推荐，输入问题，发送【Enter】/ 换行【Shift+Enter】'
                  : '输入问题，发送【Enter】/ 换行【Shift+Enter】'
                : '输入问题'
            }
            style={textareaStyle}
          />
        </AutoComplete>
      </div>

      <div className="flex justify-between">
        <div className="flex items-center justify-center">
          <Button
            style={{
              borderColor: isDeepMode ? '#6640FF' : '#E0E0E0',
              color: isDeepMode ? '#6640FF' : '#4C4C4C',
              backgroundColor: isDeepMode ? '#DBE9FE' : '#fff',
              margin: '5px',
            }}
            onClick={() => {
              setIsDeepMode(!isDeepMode);
            }}
          >
            <SvgIcon icon="deep-mode" size={20} color={isDeepMode ? '#6640FF' : '#4C4C4C'} />
            深度思考
          </Button>
        </div>

        {isHome ? (
          // <Button
          //   className="flex "
          //   id="submit"
          //   type="text"
          //   size="small"
          //   icon={<SvgIcon icon="ic_rj_send" size={20} />}
          //   onClick={handleBtnClicked}
          //   disabled={inputValue ? false : true}
          //   style={{
          //     color: '#fff',
          //     borderRadius: '16px',
          //     width: '40px',
          //     height: '30px',
          //     backgroundColor: inputValue ? '#6640ff' : '#eee',
          //     display: 'flex',
          //     justifyContent: 'center',
          //     alignItems: 'center',
          //     alignSelf: 'flex-end',
          //     justifySelf: 'end',
          //     margin:'5px 10px'
          //   }}
          // />
          <Button
            className="flex"
            id="submit"
            type="text"
            size="small"
            icon={
              isMessageSend ? (
                <SvgIcon icon="ic_stop" size={25} />
              ) : inputValue.trim().length == 0 ? (
                initializeData?.license_edition == LicenseEditionEnum?.basic
                  ?
                  <SvgIcon icon="ic_rj_send" size={25} />
                  :
                  voice ? (
                    <SvgIcon icon="ic_rj_keyboard" size={25} />
                  ) : (
                    <SvgIcon icon="ic_rj_sound" size={25} />
                  )
              ) : (
                <SvgIcon icon="ic_rj_send" size={25} />
              )
            }
            onClick={handleBtnClicked}
            style={{
              color: '#fff',
              borderRadius: '16px',
              width: isPc ? '60px' : '50px',
              height: '30px',
              backgroundColor: isDisabled ? '#CCCCCC' : '#6640ff',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              alignSelf: 'flex-end',
              justifySelf: 'end',
              margin: '5px 0px',
            }}
            disabled={isDisabled}
          />
        ) : (
          <Button
            className="flex"
            id="submit"
            type="text"
            size="small"
            icon={
              isMessageSend ? (
                <SvgIcon icon="ic_stop" size={25} />
              ) : inputValue.trim().length == 0 ? (
                initializeData?.license_edition == LicenseEditionEnum?.basic
                  ?
                  <SvgIcon icon="ic_rj_send" size={25} />
                  :
                  voice ? (
                    <SvgIcon icon="ic_rj_keyboard" size={25} />
                  ) : (
                    <SvgIcon icon="ic_rj_sound" size={25} />
                  )
              ) : (
                <SvgIcon icon="ic_rj_send" size={25} />
              )
            }
            onClick={handleBtnClicked}
            style={{
              color: '#fff',
              borderRadius: '16px',
              width: isPc ? '60px' : '50px',
              height: '30px',
              backgroundColor: isDisabled ? '#CCCCCC' : '#6640ff',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              alignSelf: 'flex-end',
              justifySelf: 'end',
              margin: '5px 0px',
            }}
            disabled={isDisabled}
          />
        )}
      </div>
      <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
    </div>
  );
};

export default memo(MessageSendInput);
